<!--
  * 商品列表
  *
-->
<template>
  <a-card size="small" :bordered="false" :hoverable="true" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <!---------- 查询表单form begin ----------->
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="6">
          <a-form-item label="商品名称" class="smart-margin-bottom0">
            <a-input v-model:value.trim="keyword" placeholder="商品名称、助记码" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="商品编码" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="商品编码" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="品牌" class="smart-margin-bottom0">
            <Select name="Brand" v-model:value="queryForm.company_brand_id" placeholder="品牌" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->
  <!---------- 表格操作行 begin ----------->
  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="addGoods()" type="primary" v-privilege="'goods:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <!-- <a-button @click="deleteData(selectedRowKeyList)" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'goods:batchDelete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button> -->

        <a-button @click="showImportModal" primary v-privilege="'goods:importGoods'">
          <template #icon>
            <ImportOutlined />
          </template>
          导入
        </a-button>

        <a-button @click="onExportGoods" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :loading="tableLoading" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'goods_name'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'img'">
            <div class="smart-table-operate">
              <a-image :width="30" :src="text || failImg" />
            </div>
          </template>
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="text === 1 ? 'blue' : 'red'">
              {{ text === 1 ? '标品' : '非标品' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'price'">
            {{ record.spec.find((item) => item.unit_type === record.default_unit_type)?.sale_price ?? '' }}
          </template>
          <template v-if="column.dataIndex === 'agree_price'">
            {{ record.spec.find((item) => item.unit_type === record.default_unit_type)?.agree_price ?? '' }}
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'">详情</a-button>
              <!-- <a-button @click="addGoods(record)" type="link" v-privilege="'goods:update'">编辑</a-button>
              <a-button @click="deleteData(record.id, record.goods_name)" danger type="link" v-privilege="'goods:delete'">删除</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>
  <!-- 导入/导出 -->
  <importModal ref="importModalRef" @downloadExcel="goodsApi.downloadExcel" :import-excel="goodsApi.importGoods" @reloadList="queryData" />
  <!-- 新增/编辑 -->
  <GoodsFormModal ref="formModal" @reloadList="queryData" />
  <!-- 详情 -->
  <GoodsDetailsModal ref="detailRef" />
</template>
<script setup lang="ts">
import GoodsFormModal from './components/goods-form-modal.vue'
import GoodsDetailsModal from './components/goods-details-modal.vue'
import { goodsApi } from '@/api/business/shopping-mall/product-api'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import importModal from '@/components/support/import-modal/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import failImg from '@/assets/images/notice/failImg.png'
import Select from '@/components/business/select/index.vue'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/shopping/product/product-event-name'
const appConfigStore = useAppConfigStore()

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------
const columns = computed(() => [
  {
    title: '图片',
    dataIndex: 'img',
    width: 80
  },
  {
    title: '商品名称',
    dataIndex: 'goods_name'
  },
  {
    title: '助记码',
    dataIndex: 'memo_code'
  },
  {
    title: '商品类型',
    dataIndex: 'type'
  },
  {
    title: '商品编码',
    dataIndex: 'no',
    width: 200
  },
  {
    title: '品牌',
    dataIndex: ['brand', 'brand_name'],
    width: 100
  },
  {
    title: '分类',
    dataIndex: ['cate', 'cate_name']
  },
  {
    title: '售价',
    dataIndex: 'price'
  },
  {
    title: '货值',
    dataIndex: 'agree_price'
  },
  {
    title: '录入时间',
    dataIndex: 'create_time'
  },
  {
    title: '创建者',
    dataIndex: ['creator', 'username'],
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right'
  }
])

// ------------------------------- 导出和导入 ---------------------------------
const importModalRef = ref()
const showImportModal = () => {
  importModalRef.value.showImportModal()
}

// 导出
const onExportGoods = () => {
  const filter = {
    goods_name: queryForm.value.goods_name,
    no: queryForm.value.no,
    company_brand_id: queryForm.value.company_brand_id
  }
  const op = {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    company_brand_id: QUERY_FORM_OP['全等查询']
  }
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(op),
    cate_id: company_cate_id.value
  }
  goodsApi.exportGoods(data)
}

// ---------------------------- 查询数据表单和方法 ----------------------------
const company_cate_id = ref(undefined)
const keyword = ref()
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      cate_id: company_cate_id.value,
      keyword: keyword.value
    }
    const res = await goodsApi.queryList(data)
    // 对 options.value 按照 item.goods_name 的首字母排序，数字开头的放后边按数字大小排序，忽略开头空格
    res.data.data.sort((a, b) => {
      // 去除 goods_name 开头的空格
      const aTrimmedName = a.goods_name.trimStart()
      const bTrimmedName = b.goods_name.trimStart()

      const aFirstChar = aTrimmedName.charAt(0)
      const bFirstChar = bTrimmedName.charAt(0)
      const isADigit = !isNaN(Number(aFirstChar))
      const isBDigit = !isNaN(Number(bFirstChar))

      if (isADigit && !isBDigit) {
        return 1 // a 是数字开头，b 不是，a 排在 b 后面
      } else if (!isADigit && isBDigit) {
        return -1 // a 不是数字开头，b 是，a 排在 b 前面
      } else if (isADigit && isBDigit) {
        // 都是数字开头，只取首数字按大小排序
        const aNumber = Number(aFirstChar)
        const bNumber = Number(bFirstChar)
        return aNumber - bNumber
      } else {
        // 都不是数字开头，按首字母排序
        return aTrimmedName.localeCompare(bTrimmedName)
      }
    })
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await goodsApi.delete({ id })
    return !!res
  },
  queryFormFilter: {
    goods_name: '',
    no: '',
    company_brand_id: null
  },
  queryFormOp: {
    goods_name: QUERY_FORM_OP['模糊查询'],
    no: QUERY_FORM_OP['模糊查询'],
    company_brand_id: QUERY_FORM_OP['全等查询']
  }
})
eventEmitter.on(customEventName.QueryProductList, ({ cate_id }) => {
  company_cate_id.value = cate_id
  queryData()
})
onMounted(queryData)

const resetQueryData = () => {
  company_cate_id.value = undefined
  keyword.value = ''
  resetQuery()
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function addGoods(goodsData) {
  formModal.value.showDrawer(goodsData)
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}
</script>
<style lang="less" scoped>
.smart-query-form {
  --grid-column-col: 4;
  padding-left: 0;
  padding-right: 0;
}
</style>
